package others;

public class CircleLinkList {
    public static void main(String[] args) {
        Node stringNode = new Node("123",null);
        Node stringNode1 = new Node("1234",null);
        Node stringNode2 = new Node("12345",null);
        Node stringNode3 = new Node("123456",null);
        Node stringNode4 = new Node("1234567",null);
        Node stringNode5 = new Node("12345678",null);
        Node stringNode6 = new Node("123456789",null);
        stringNode.next=stringNode1;
        stringNode1.next=stringNode2;
        stringNode2.next=stringNode3;
        stringNode3.next=stringNode4;
        stringNode4.next=stringNode5;
        stringNode5.next=stringNode6;
        stringNode6.next=stringNode2;
        System.out.println(getCircle(stringNode));
        System.out.println(getEntrance(stringNode).date);
    }
    public static boolean getCircle(Node first){
        Node fast = first;
        Node slow = first;
        while (fast!=null&&fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
            if (fast.equals(slow)){
                return true;
            }
        }
        return false;
    }
    public static Node getEntrance(Node first){
        Node fast = first;
        Node slow = first;
        Node curr = null;
        while (fast!=null&&fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
            if (fast.equals(slow)){
                curr=first;
                continue;
//                while (fast!=null&&fast.next!=null){
//                    fast=fast.next.next;
//                    curr=curr.next;
//                    slow=slow.next;
//                    if (curr==slow){
//                        return slow;
//                    }
//                }
            }
            if (curr!=null){
                curr=curr.next;
                if (curr.equals(slow)){
                    break;
                }
            }
        }
        return curr;
    }
    private static class Node<T>{
        private T date;
        private Node next;

        public Node(T date, Node next) {
            this.date = date;
            this.next = next;
        }
    }
}
